Overload subscript operator [] in C ++

The subscript operator [] in C ++ is often used to access array elements. This operator can be overloaded to enhance existing functionality in arrays in C ++.

The subscript operator [] in C ++ is often used to access array elements. This operator can be overloaded to enhance an existing feature of arrays in C ++ (so it can be called an array index operator).

The following example illustrates how to load the subscript operator [] in C ++:

 #include using namespace std ; const int KICHCO = 15 ; class ViDuMang { private : int mang [ KICHCO ]; public : ViDuMang () { register int i ; for ( i = 0 ; i < KICHCO ; i ++) { mang [ i ] = i ; } } int & operator []( int i ) { if ( i > KICHCO ) { cout << "n======================n" << endl ; cout << "Chi muc vuot gioi han!!" << endl ; // Tra ve phan tu dau tien. return mang [ 0 ]; } return mang [ i ]; } }; int main () { ViDuMang V ; cout << "Gia tri cua V[3] la: " << V [ 3 ] << endl ; cout << "Gia tri cua V[6] la: " << V [ 6 ]<< endl ; cout << "Gia tri cua V[16] la: " << V [ 16 ]<< endl ; return 0 ; } 

Compiling and running the above C ++ program will produce the following results:

Overload subscript operator [] in C ++ Picture 1Overload subscript operator [] in C ++ Picture 1

According to Tutorialspoint

Previous article: Load the operator stack call the function () in C ++

Next lesson: Overload member access operator (->) in C ++

4 ★ | 1 Vote